package com.example.yyy

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.widget.ProgressBar

class TextProgressBar @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyle: Int = 0)
    : ProgressBar(context,attrs,defStyle){

    private var progressText = ""
    private var paint:Paint
    private var textColor = Color.BLACK
    private var textSize = 30f

    fun text(text:String){
        progressText=text
        invalidate()
    }

    init {
        //初始化画笔
        paint = Paint()
        paint.color = textColor
        paint.textSize = textSize
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val rect = Rect()
        //获取进度文本的矩形边界
        paint.getTextBounds(progressText,0,progressText.length,rect)
        val x =width/2-rect.centerX()
        val y =height/2-rect.centerY()
        canvas?.drawText(progressText,x.toFloat(),y.toFloat(),paint)
    }
}